package cj.primariaiquest.web;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cj.primariaiquest.model.Department;
import cj.primariaiquest.model.Ticket;
import cj.primariaiquest.schemas.TicketResponse;
import cj.primariaiquest.ws.endpoint.WebServiceClient;
import cj.primariaiquest.ws.exceptions.WebServiceException;

/**
 * Web controller used to handle /ticketOrder request
 * 
 * @author georgian.parvu
 * 
 */
@Component
public class TicketServlet extends HttpServlet {

    private static final long serialVersionUID = -6336843870510415269L;

    /**
     * Web service client used to send requests to the web service.
     */
    private static WebServiceClient webServiceClient;

    @Autowired
    public void setWebServiceClient(WebServiceClient webServiceClient) {
	TicketServlet.webServiceClient = webServiceClient;
    }

    /**
     * When Submit button is pressed, this method will handle the data. If there
     * is a number available it will be displayed, else redirect the page to
     * ticket failure page.
     * 
     */
    @Override
    protected void doGet(HttpServletRequest request,
	    HttpServletResponse response) throws ServletException, IOException {
	String address = "/WEB-INF/jsp/showTicketNumber.jsp";
	String dep = request.getParameter("dep");
	TicketResponse ticketResponse = null;

	try {
	    ticketResponse = webServiceClient.sendTicketRequestAndReceive(dep);
	} catch (WebServiceException e) {
	    address = "/WEB-INF/jsp/ticketFailure.jsp";

	}

	Ticket ticket = new Ticket();
	ticket.setDepartment(Department.valueOf(dep));

	if (ticketResponse != null) {
	    ticket.setNumber(ticketResponse.getNumber());
	}
	request.setAttribute("ticket", ticket);

	RequestDispatcher dispatcher = request.getRequestDispatcher(address);
	dispatcher.forward(request, response);
    }
}
